package org.test.device.config.mqtt;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.test.device.vo.device.DeviceReceiveInfo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 〈接收信息〉<br>
 *
 * @author Mr.Wang
 * @create 2025/9/29
 */
@Component
public class MqttReceiver {


    @Autowired(required = false)
    private SimpMessagingTemplate webSocketTemplate;

    //信息存储
    private final Map<String, List<DeviceReceiveInfo>> topicMessages = new ConcurrentHashMap<>();


    /**
     * @param payload 消息内容
     * @Author Mr.Wang
     * @Description 处理接收到的MQTT消息（基础版）会自动接收配置的订阅主题消息
     * @Date 16:15 2025/9/29
     **/
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleBasicMqttMessage(String payload) {
        System.out.println("收到MQTT消息: " + payload);
    }

    /**
     * @param topic   消息主题
     * @param payload 消息内容
     * @Author Mr.Wang
     * @Description 处理接收到的MQTT消息（带主题信息）可以获取消息来源的主题
     * @Date 16:15 2025/9/29
     **/
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMqttMessage(
            @Header(MqttHeaders.TOPIC) String topic,
            String payload) {
        try {
            // 解析消息为DeviceReceiveInfo对象
            DeviceReceiveInfo message = JSON.parseObject(payload, DeviceReceiveInfo.class);
            message.setReceiveTime(new Date()); // 设置接收时间
            message.setSource("mqtt"); // 标记来源

            // 存入消息列表
            getMessagesByTopic(topic).add(message);

            // 通过WebSocket实时推送给前端
            if (webSocketTemplate != null) {
                Map<String, Object> pushData = new HashMap<>();
                pushData.put("topic", topic);
                pushData.put("message", message);
                pushData.put("timestamp", System.currentTimeMillis());
                webSocketTemplate.convertAndSend("/topic/mqtt/" + topic, pushData);
            }

            System.out.println("MQTT接收消息 - 主题: " + topic + ", 内容: " + payload);
        } catch (Exception e) {
            System.err.println("处理MQTT消息失败: " + e.getMessage());
        }
    }


    /**
    * @Author Mr.Wang
    * @Description 提供获取消息的方法给Service
    * @Date 16:35 2025/9/29
    * @param
    **/
    public List<DeviceReceiveInfo> getMessagesByTopic(String topic) {
        return topicMessages.computeIfAbsent(topic, k -> new CopyOnWriteArrayList<>());
    }
}